package config;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;

import app.AppGlobals;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ConfigHandler {
	
	public static LauncherConfig generateNewConfigFile(){
		LauncherConfig config = new LauncherConfig();
		AppGlobals.launcherConfig = config;
		return config;
	}
	
	public static void saveCurrentConfig(){
		createXMLConfigFile();
	}
	
	public static void createXMLConfigFile(){
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("launcherConfig", LauncherConfig.class);
		String xml = xstream.toXML(AppGlobals.launcherConfig);
		
		writeXMLConfigToFile(xml);
	}
	
	
	public static Boolean writeXMLConfigToFile(String xml){
		if(xml == "") return false;
		PrintWriter out;
		try {
			out = new PrintWriter(".//launcher.cfg");
			out.println(xml);
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return true;
	}
	
	public static String getXMLStringFromFile(){
		String xml = "";
		xml = readFile(".//launcher.cfg");
		return xml;
	}
	
	public static Boolean loadConfigFile(String xml){
			
		
		if(xml == "") return false;
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("launcherConfig", LauncherConfig.class);
		LauncherConfig config = (LauncherConfig)xstream.fromXML(xml);
		if(config == null)
			return false;
		
		AppGlobals.launcherConfig  = config;
		return true;
	}

	
	public static String readFile(String filename) {
		File f = new File(filename);
		if(!f.exists()) return "";
		try {
			byte[] bytes = Files.readAllBytes(f.toPath());
			return new String(bytes,"UTF-8");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

}
